const express=require('express'),
    path=require('path'),
    fs=require('fs'),
    os=require('os'),
    MarkdownIt=require('markdown-it'),
    swig=require('swig'),
    md=new MarkdownIt({html:true,langPrefix:'code-'});

swig.setDefaults({cache:false});

module.exports=(dir='.')=>{
    console.log('preview dir:',dir);
    let app=express(),
        router=express.Router();

    app.use(express.static(path.join(dir,'assets')));

    app.use(router);

    //blog
    router.get('/posts/*',(req,res,next)=>{
        let name=req.params[0],
            file=path.join(dir,'_posts',name+'.md');
        console.log('name:',name,'file:',file);

        fs.readFile(file,(err,data)=>{
            if(err)return next(err);
            res.type('text/html;charset=utf8');
            let post=parseSource(data.toString());
            post.content=markdownToHtml(post.body);
            post.layout=post.layout || 'post';
            console.log('post:',post);
            let html=renderFile(path.join(dir,'_layout',post.layout+'.html'),{post});
            res.end(html);
        });
    });

    //list
    router.get('/',(req,res,next)=>res.end('Blog list.'));

    app.listen(3000,()=>console.log('Blog @3000----'+new Date()));
};

function renderFile(file,data) {
    return swig.render(fs.readFileSync(file).toString(),{
        filename:file,
        autoescape:false,
        locals:data
    });
}


function markdownToHtml(data='') {
    return md.render(data);
}

function parseSource(data) {
    const info={};
    let reg=/\-{3,}\s+(\b[\s\S]+\b)\s+\-{3,}([\s\S]+)/;
    let ret=data.match(reg);
    console.log(ret);
    if(!ret)return info;
    info.body=ret[2].trim();
    ret=ret[1];
    ret=ret.split(os.EOL);
    ret.forEach(line=>{
        let p=line.match(/(.+):(.+)/);
        if(!p)return;
        info[p[1]]=p[2];
    });
    return info;
}